package jianzhi

func isBalanced(root *TreeNode) bool {

	if root == nil {
		return true
	}

	isLeft := isBalanced(root.Left)
	isRight := isBalanced(root.Right)

	if !isLeft || !isRight {
		return false
	}

	leftDepth := depth(root.Left)
	rightDepth := depth(root.Right)

	if abs(rightDepth-leftDepth) > 1 {
		return false
	}

	return true
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func depth(root *TreeNode) int {
	if root == nil {
		return 0
	}

	leftDepth := depth(root.Left)
	rightDepth := depth(root.Right)

	if leftDepth > rightDepth {
		return leftDepth + 1
	}

	return rightDepth + 1

}
